package com.hub.eshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hub.eshop.entity.NewBeeMallGoods;
import com.hub.eshop.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CacheServiceImpl implements CacheService {

    public static final String CACHE_NAME = "local";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @CachePut(value = CACHE_NAME, key = "'newBeeMallGoods_'+#newBeeMallGoods.getGoodsId()")
    public NewBeeMallGoods saveProductInfo2LocalCache(NewBeeMallGoods newBeeMallGoods) {
        return newBeeMallGoods;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'newBeeMallGoods_'+#goodsId")
    public NewBeeMallGoods getProductInfoFromLocalCache(Long goodsId) {
        return null;
    }

    @Override
    public void saveProductInfo2ReidsCache(NewBeeMallGoods newBeeMallGoods) {
        redisTemplate.opsForValue().set("goods_id_"+newBeeMallGoods.getGoodsId(), newBeeMallGoods);
    }

    @Override
    public NewBeeMallGoods getProductInfoFromReidsCache(Long goodsId) {
        Object o = redisTemplate.opsForValue().get("goods_id_"+goodsId);
        if(o==null){
            return null;
        }
        JSONObject jo =(JSONObject) o;
        NewBeeMallGoods newBeeMallGoods = jo.toJavaObject(NewBeeMallGoods.class);
        return newBeeMallGoods;
    }
}
